<template>
  <el-container direction="vertical">
    <header
      style="min-height:180px;"
      class="el-header"
    >
      <el-form
        ref="form"
        label-width="100px"
        style="margin-top:20px;"
        @submit.native.prevent
      >
        <el-row>
          <el-col :span="6">
            <el-form-item label="姓名：">
              <el-input
                v-model="search.cNickname"
                maxlength="30"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门：">
              <el-select
                v-model="search.departmentId"
                clearable
                onselect="return"
                placeholder="全部"
                filterable
              >
                <el-option
                  v-for="item in department"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系方式：">
              <el-input
                v-model="search.cPhone"
                maxlength="20"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="警号：">
              <el-input
                v-model="search.cUsername"
                maxlength="30"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职位：">
              <el-select
                v-model="search.cJobnumber"
                clearable
                placeholder="全部"
              >
                <!-- <el-option value="">全部</el-option> -->
                <el-option value="民警">民警</el-option>
                <el-option value="协警">协警</el-option>
                <el-option value="主要负责人">主要负责人</el-option>
                <el-option value="负责人">负责人</el-option>
                <el-option value="外部联系人">外部联系人</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
                <el-form-item label="身份证号码：">
                  <el-input v-model="search.cCardId" maxlength="30"></el-input>
                </el-form-item>
          </el-col>-->
          <el-col :span="6">
            <el-form-item label="角色：">
              <el-select
                v-model="search.roleId"
                clearable
                onselect="return"
                placeholder="全部"
              >
                <el-option
                  v-for="item in role"
                  :key="item.cRoleId"
                  :label="item.cRoleName"
                  :value="item.cRoleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="6">

          </el-col>-->

          <el-col :span="10">
            <el-form-item>
              <el-button @click="query(search)">查询</el-button>
              <!-- <el-button class="querybtn" type="primary" @click="$router.push('/User/useradd')">添加</el-button> -->
              <el-button
                type="primary"
                @click="handleAdd"
              >新增</el-button>
            </el-form-item>
            <el-dialog
              :title="title"
              :visible.sync="dialogFormVisible"
            >
              <el-form
                :model="user"
                ref="form"
                class="demo-ruleForm"
                label-width="90px"
              >
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      label="姓名："
                      prop="cNickname"
                      :rules="[{required:true, message:'请输入姓名',trigger:'blur'}]"
                    >
                      <el-input
                        v-model="user.cNickname"
                        auto-complete="off"
                        maxlength="30"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="警号："
                      prop="cUsername"
                      :rules="[{required:true, message:'请输入警号',trigger:'blur'}]"
                    >
                      <el-input
                        v-model="user.cUsername"
                        type="text"
                        maxlength="30"
                        :disabled="title==='修改'"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      label="职位："
                      prop="cJobnumber"
                      :rules="[{required:true, message:'请输入警号',trigger:'change'}]"
                    >
                      <el-select
                        v-model="user.cJobnumber"
                        @change="onJobChange"
                      >
                        <el-option value="民警">民警</el-option>
                        <el-option value="协警">协警</el-option>
                        <el-option value="主要负责人">主要负责人</el-option>
                        <el-option value="负责人">负责人</el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="业务口："
                      prop="businessflag"
                      :rules="[{validator:validatePort,trigger:'change'}]"
                    >
                      <el-select
                        v-model="user.businessflag"
                        multiple
                        placeholder="请选择业务口"
                        :disabled="user.cJobnumber!=='负责人'"
                      >
                        <el-option
                          v-for="item in bussinessData"
                          :key="item.id"
                          :label="item.name"
                          :value="parseInt(item.id,10)"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      label="联系方式："
                      prop="cPhone"
                      :rules="[{required:true, message:'请输入联系方式',trigger:'blur'}]"
                    >
                      <el-input
                        v-model="user.cPhone"
                        maxlength="30"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="角色："
                      prop="roleId"
                      :rules="[{required:true, message:'请选择角色',trigger:'change'}]"
                    >
                      <el-select
                        v-model="user.roleId"
                        onselect="true"
                        placeholder="请选择角色"
                      >
                        <el-option
                          v-for="item in role"
                          :key="item.cRoleId"
                          :label="item.cRoleName"
                          :value="item.cRoleId"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item
                      label="部门："
                      prop="departmentLevel"
                      :rules="{required:true,message:'请选择部门',trigger:'change'}"
                    >
                      <el-select
                        onselect="return"
                        placeholder="选择部门级别"
                        v-model="user.departmentLevel"
                        @change="onLevelChange"
                      >
                        <el-option
                          v-for="item in departLevels"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item>
                      <el-select
                        v-model="selectedDepart2"
                        @change="onLevel2Change"
                      >
                        <el-option
                          v-for="item in departs2"
                          :key="item.id"
                          :value="item.id"
                          :label="item.name"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item v-if="user.departmentLevel===3">
                      <el-select
                        v-model="selectedDepart3"
                        @change="onLevel3Change"
                      >
                        <el-option
                          v-for="item in departs3"
                          :key="item.id"
                          :value="item.id"
                          :label="item.name"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label="密码："
                      prop="cPassword"
                      v-if="title==='添加'"
                      :rules="[{validator:validatePass1,required:true, trigger:'change'}]"
                    >
                      <el-input
                        v-model="user.cPassword"
                        maxlength="30"
                      ></el-input>
                    </el-form-item>
                    <el-form-item
                      label="密码："
                      prop="cPassword"
                      v-else
                      :rules="[{validator:validatePass2, trigger:'change'}]"
                    >
                      <el-input
                        v-model="user.cPassword"
                        maxlength="30"
                      ></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <div
                slot="footer"
                class="dialog-footer"
                style="   text-align: center"
              >
                <el-button @click="quxiao">取 消</el-button>
                <el-button
                  type="danger"
                  @click="save()"
                >确 定</el-button>
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </el-form>
    </header>
    <el-main style="height:720px">
      <section class="contant_head">
        <span>图表
          <!-- <sub>Form</sub> -->
        </span>
      </section>
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 98%;margin:10px;text-align:center;"
        :header-cell-style="getRowClass"
      >
        <el-table-column
          type="index"
          label="编号"
        ></el-table-column>
        <el-table-column
          prop="cNickname"
          label="姓名"
        ></el-table-column>
        <el-table-column
          prop="cUsername"
          label="警号"
        ></el-table-column>
        <el-table-column
          prop="departmentname"
          label="部门"
        ></el-table-column>
        <!-- <el-table-column prop="cCardId" label="身份证号码"></el-table-column> -->
        <el-table-column
          prop="cJobnumber"
          label="职位"
        ></el-table-column>
        <el-table-column
          prop="cPhone"
          label="联系电话"
        ></el-table-column>
        <el-table-column
          prop="rolename"
          label="角色"
        ></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
        ></el-table-column>
        <el-table-column
          fixed="right"
          label="操作"
          width="320"
        >
          <template slot-scope="scope">
            <!-- <el-button
              class="edit-btn"
              @click="handleEdit(scope.$index, scope.row)"
              size="medium"
              type="info"
            >重置密码</el-button> -->
            <el-button
              class="edit-btn"
              @click="handleEdit(scope.$index, scope.row)"
              size="medium"
            >
              <i></i>修改
            </el-button>
            <el-button
              :id="gitButtonId(scope.$index+1)"
              class="edit-btn"
              size="medium"
              v-show="scope.row.cUsername==='admin'?false:true"
              @click="handleStop(scope.row)"
            >
              <label v-if="scope.row.state===0">启用</label>
              <label v-else>禁用</label>
            </el-button>
            <el-button
              class="edit-btn"
              @click="handleDelete(scope.$index, scope.row)"
              v-show="scope.row.cUsername==='admin'?false:true"
              type="danger"
              size="medium"
            >
              <i></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[ 10]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next"
          :total="total"
          style="float:right"
        ></el-pagination>
      </div>
    </el-main>
  </el-container>
</template>
<script>
import { api } from "@/fetch/api";

export default {
  name: "user",
  data() {
    return {
      options: [
        {
          value: 0,
          label: "全选"
        },
        {
          value: 1,
          label: "启用"
        },
        {
          value: 2,
          label: "禁用"
        }
      ],
      departs2: [],
      departs3: [],
      selectedDepart2: "",
      selectedDepart3: "",
      selectedId: "",
      selectedType: "",
      selectedName: "",
      departLevels: [
        {
          value: 1,
          label: "一级部门"
        },
        {
          value: 2,
          label: "二级部门"
        },
        {
          value: 3,
          label: "三级部门"
        }
      ],
      form: {
        name: "",
        zubie: "",
        email: "",
        juese: "",
        gonghao: "",
        phone: "",
        region: "",
        date1: "",
        date2: "",
        username: ""
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
      currentPage: 1, //當前頁碼
      limit: 10,
      total: null,
      edit: false,
      formLabelWidth: "120px",
      role: api.LocalStorageService.get("role"),
      department: '',
      search: {
        cCardId: "",
        cJobnumber: "",
        cNickname: "",
        cOperatorId: 0,
        cOperatorUser: "",
        cPassword: "",
        cPhone: "",
        cUserId: 0,
        cUsername: "",
        createTime: "",
        department: {
          cDepartmentId: 0,
          cDepartmentName: "",
          createTime: "",
          endDate: "",
          remark: "",
          startDate: "",
          state: 0,
          updateTime: ""
        },
        departmentId: "",
        endDate: "",
        limit: 0,
        offset: 0,
        remark: "",
        roleId: "",
        startDate: "",
        state: 0,
        updateTime: ""
      },
      user: {
        cNickname: "",
        cUsername: "",
        cJobnumber: "",
        roleId: "",
        cPhone: "",
        cPassword: "",
        departmentLevel: "",
        businessflag: []
      },
      title: "tghgh",
      startDate: null,
      endDate: null,
      tableData: [],
      bussinessData: []
    };
  },
  methods: {
    gitButtonId(index) {
      return index;
    },
    onJobChange(val) {
      this.user.businessflag = [];
      if (val === "负责人") {
        api.findDepartment(0, 0, { type: 2 }).then(res => {
          if (res.status === 100) {
            this.bussinessData = res.result.inspectorList;
          }
        });
      }
    },
    handleStop(row) {
      const status = row.state === 0 ? 1 : 0;
      api
        .UserModifyStatus({
          state: status,
          userID: row.cUserId
        })
        .then(response => {
          if (response.status === 100) {
            //如果成功
            this.getUser(10, this.currentPage);
          } else {
            this.$message.error(response.message);
          }
        });
    },
    quxiao() {
      this.dialogFormVisible = !this.dialogFormVisible;
      this.getUser(10, this.currentPage);
    },
    getRowClass({ row, column, rowIndex, columnIndex }) {
      if (rowIndex == 0) {
        return "background:rgba(242,242,242,1)";
      } else {
        return "";
      }
    },
    save() {
      this.$refs.form.validate(valid => {
        if (valid && (this.selectedId || this.user.departmentId)) {
          if (this.title === "添加") {
            const values = { ...this.user };
            values.departmentId = this.selectedId;
            values.departmentType = this.selectedType;
            values.usertype = 1;
            // values.departmentname = this.selectedName
            if (!values.businessflag.length) {
              values.businessflag = null;
            } else {
              values.businessflag = values.businessflag.join(",");
            }
            api.AddUser(values).then(response => {
              if (response.status === 100) {
                this.$message.success("添加成功");
                this.dialogFormVisible = !this.dialogFormVisible;
                this.getUser(10, this.currentPage);
              } else {
                this.$message.error("添加错误");
              }
            });
          } else {
            const {
              cNickname,
              cUsername,
              cJobnumber,
              cPhone,
              cPassword,
              departmentLevel,
              departmentId,
              departmentType,
              roleId,
              cUserId,
              businessflag
            } = this.user;
            const values = {
              cNickname,
              cJobnumber,
              cPhone,
              cPassword,
              roleId,
              cUserId,
              departmentLevel,
              departmentType,
              departmentId,
              businessflag
            };
            if (this.selectedId) {
              values.departmentId = this.selectedId;
            }
            values.usertype = 1;
            values.departmentType = this.selectedType;
            // values.departmentname = this.selectedName
            if (!values.businessflag || !values.businessflag.length) {
              values.businessflag = null;
            } else {
              values.businessflag = values.businessflag.join(",");
            }
            api.UserModify(values).then(response => {
              if (response.status === 100) {
                this.$message.success("修改成功");
                this.dialogFormVisible = !this.dialogFormVisible;
                this.getUser(10, this.currentPage);
              } else {
                this.$message.error("修改错误");
              }
            });
          }
        } else {
          this.$message({
            type: "warning",
            message: "请完善表单"
          });
        }
      });
    },
    getPermission(limit, pageIndex) {
      api
        .PermissionPage({}, { limit: 10, pageIndex: pageIndex })
        .then(response => {
          if (response.status === 100) {
            this.permissions = response.result.list;
            api.LocalStorageService.update("permissions", response.result.list);
          } else {
          }
        })
        .catch(error => { });
    },
    getRole(limit, pageIndex) {
      api
        .RolePage({}, { limit: 10, pageIndex: pageIndex })
        .then(response => {
          if (response.status === 100) {
            this.role = response.result.list;
            api.LocalStorageService.update("role", response.result.list);
          } else {
            this.$message.error(response.message);
          }
        })
        .catch(error => {
          this.$message.error(error);
        });
    },
    getDepattment(limit = 10, pageIndex) {
      api
        .findDepartment(0, 0)
        .then(res => {
          this.department = res.result.inspectorList;
        })
        .catch(error => {
          this.$message.error(error);
        });
    },
    getUser(limit, pageIndex) {
      api
        .UserPage(this.search, { pageSize: 10, currPage: pageIndex })
        .then(response => {
          if (response.status === 100) {
            this.tableData = response.result.inspectorList;
            this.total = response.result.totalCount;
          } else {
            this.$message.error(response.message);
          }
        });
    },
    query(search) {
      api.UserPage(search, { pageSize: 10, currPage: 1 }).then(response => {
        if (response.status === 100) {
          this.tableData = response.result.inspectorList;
          this.currentPage = 1;
          this.total = response.result.totalCount;
        } else {
        }
      });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getUser(this.limit, val);
    },
    handleSizeChange(val) {
      this.limit = val;
      this.getUser(val, this.currentPage);
    },
    handleDelete(index, row) {
      this.$confirm("是否继续删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          api.DeleteUser(row.cUserId).then(response => {
            if (response.status === 100) {
              this.$message.success(response.message);
              this.getUser(this.limit, this.currentPage);
            } else {
            }
          });
        })
        .catch(() => { });
    },
    handleAdd() {
      this.dialogFormVisible = !this.dialogFormVisible;
      this.user = {
        cNickname: "",
        cUsername: "",
        cJobnumber: "",
        roleId: "",
        cPhone: "",
        cPassword: "",
        departmentLevel: "",
        businessflag: []
      };
      this.selectedDepart2 = "";
      this.selectedDepart3 = "";
      this.departs2 = [];
      this.departs3 = [];
      this.title = "添加";
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    handleEdit(index, row) {
      this.user = { ...row };
      this.user.cPassword = "";
      this.dialogFormVisible = !this.dialogFormVisible;
      this.title = "修改";
      if (this.user.cJobnumber === "负责人") {
        const ids = this.user.businessflag
          ? this.user.businessflag.split(",")
          : [];

        this.user.businessflag = [];
        ids.map(item => {
          this.user.businessflag.push(parseInt(item, 10));
        });
        api.findDepartment(0, 0, { type: 2 }).then(res => {
          if (res.status === 100) {
            this.bussinessData = res.result.inspectorList;
          }
        });
      }
      this.onLevelChange(this.user.departmentLevel);
      if (this.user.departmentLevel === 1) {
        this.selectedDepart2 = this.user.departmentId;
        api.findDepartment(0, 0, { type: 1 }).then(res => {
          this.departs2 = res.result.inspectorList;
        });
      }
      if (this.user.departmentLevel === 2) {
        this.selectedDepart2 = this.user.departmentId;
        api.getDopeDeparts().then(res => {
          this.departs2 = res.result.inspectorList;
        });
      }
      if (this.user.departmentLevel === 3) {
        this.selectedDepart3 = this.user.departmentId;
        api.findDepartmentById(this.selectedDepart3).then(res => {
          this.selectedDepart2 = res.result.fatherid;
          this.onLevel2Change(res.result.fatherid)
        });
        api
          .findDepartment(0, 0, { type: 4, fatherid: this.selectedDepart2 })
          .then(res => {
            this.departs3 = res.result.inspectorList;
          });
      }
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    onLevelChange(val) {
      this.selectedDepart2 = "";
      this.selectedType = "";
      this.selectedId = ''
      if (val === 2) {
        api.getDopeDeparts().then(res => {
          this.departs2 = res.result;
        });
      } else if (val === 3) {
        api.findDepartment(0, 0, { type: 3 }).then(res => {
          this.departs2 = res.result.inspectorList;
        });
      } else {
        api.findDepartment(0, 0, { type: 1 }).then(res => {
          this.departs2 = res.result.inspectorList;
        });
      }
    },
    onLevel2Change(val) {
      if (this.user.departmentLevel !== 3) {
        const { type, name } = this.departs2.find(item => item.id === val);
        this.selectedType = type;
        this.selectedName = name;
        this.selectedId = val;
      } else {
        this.selectedId = ''
      }
      this.selectedDepart3 = "";
      api.findDepartment(0, 0, { type: 4, fatherid: val }).then(res => {
        this.departs3 = res.result.inspectorList;
      });
    },
    onLevel3Change(val) {
      const { type, name } = this.departs3.find(item => item.id === val);
      this.selectedId = val;
      this.selectedType = type;
      this.selectedName = name;
    },
    validatePort(rules, value, cb) {
      if (this.user.cJobnumber === "负责人" && !value.length) {
        cb(new Error("请选择业务口"));
      } else {
        cb();
      }
    },
    validatePass1(rules, value, cb) {
      if (!value) {
        cb(new Error("请输入密码"));
      } else if (value && value.length < 6) {
        cb(new Error("密码不能小于6位"));
      } else {
        cb();
      }
    },
    validatePass2(rules, value, cb) {
      if (value && value.length < 6) {
        cb(new Error("密码不能小于6位"));
      } else {
        cb();
      }
    }
  },
  mounted() {
    this.getRole(10, this.currentPage);
    // this.getPermission();
    this.getDepattment(0, 0);
    this.getUser(10, this.currentPage);
    this.query(this.search);
  }
};
</script>

<style lang="less" scoped>
@import url("../../assets/css/index.css");
.el-header {
  width: 98%;
  background: #fff;
  margin: 0 auto;
  margin-top: 20px;
  margin-bottom: 20px;
  .el-input,
  .el-select,
  .el-date-picker {
    width: 100%;
  }
}
.el-main {
  width: 98%;
  background: #fff;
  margin: 0 auto;
  padding: 0px;
  .contant_head {
    border-left: 3px solid #f7585d;
    background: #f9f9f9;
    height: 40px;
    span {
      line-height: 40px;
      font-size: 20px;
      padding-left: 10px;
      sub {
        font-size: 12px;
      }
    }
  }
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
<style>
.cell {
  text-align: center;
}

.el-input__inner {
  background: rgba(255, 255, 255, 0.08);
  padding-left: 0.2rem;
  color: #333;
}
</style>
<style lang="stylus" module="$">
.role_setting_panel {
  :global {
    .el-form--inline .el-form-item {
      margin-right: 0;
    }

    .el-input--suffix .el-input__inner {
      padding-right: 14px;
    }

    .el-input--prefix .el-input__inner {
      padding-left: 48px;
    }

    .el-dialog__header {
      background: rgba(242, 242, 242, 1);
      padding-bottom: 16px;
    }

    .el-dialog__title {
      font-weight: bold;
    }

    .el-button--primary {
      color: #fff;
      background-color: #f56c6c;
      border-color: #f56c6c;
    }
  }
}
</style>

